#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <thread>
#include <mutex>

using namespace std;

void workerFunction(vector<int>& S, vector<mutex>& mtxs) {
    const int N = S.size();
    for (int k = 0; k < 10000; ++k) {
        int i = rand() % N;
        int j = rand() % N;

        // 确保索引不同
        while (j == i || j == (i + 1) % N || j == (i + 2) % N) {
            j = rand() % N;
        }

        // 使用lock_guard来自动管理锁的释放
        unique_lock<mutex> lock1(mtxs[i], defer_lock);
        unique_lock<mutex> lock2(mtxs[(i + 1) % N], defer_lock);
        unique_lock<mutex> lock3(mtxs[(i + 2) % N], defer_lock);
        unique_lock<mutex> lock4(mtxs[j], defer_lock);

        lock(lock1, lock2, lock3, lock4); // 同时获取四个锁

        int sum = S[i] + S[(i + 1) % N] + S[(i + 2) % N];
        S[j] = sum;

        // 锁将在作用域结束时自动释放
    }
}

int main() {
    const int N = 100000;
    const int M = 2;
    vector<int> S(N, 0);
    vector<mutex> mtxs(N);

    // 初始化S数组
    for (int i = 0; i < N; ++i) {
        S[i] = i; // 可以根据实际需求进行初始化
    }

    // 设置随机数种子
    srand(time(0));

    // 创建M个工作者线程
    vector<thread> workers;
    for (int worker = 0; worker < M; ++worker) {
        workers.push_back(thread(workerFunction, ref(S), ref(mtxs)));
    }

    // 等待所有工作者线程完成
    for (int worker = 0; worker < M; ++worker) {
        workers[worker].join();
    }

    // 输出更新后的S数组
    for (int i = 0; i < N; ++i) {
        cout << S[i] << " ";
    }
    cout << endl;

    return 0;
}
